package com.xge.common_libary.view

import android.content.Context
import android.util.SparseArray
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView

@Suppress("NOTHING_TO_INLINE")
open class ViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val cachedViews: SparseArray<View> by lazy { SparseArray<View>() }
    open var item: T? = null
    open val context: Context
        get() = itemView.context

    @Suppress("UNCHECKED_CAST")
    operator fun <T : View> get(@IdRes id: Int): T = getOptional(id)!!

    fun <T : View> getOptional(@IdRes id: Int): T? {
        val cachedView = cachedViews[id]
        return if (cachedView != null) {
            cachedView as T
        } else {
            val v = itemView.findViewById<View?>(id)
            if (v != null) {
                cachedViews.put(id, v)
            }
            v as T?
        }
    }

    fun <T : View> findViewById(@IdRes id: Int): T = get(id)

    fun getString(@StringRes id: Int, vararg args: Any?): String =
        context.getString(id, *args)
}
